package com.daxia.ogmall.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Repository;

import com.daxia.ogmall.daobase.GenericDAOHibernate;
import com.daxia.ogmall.dto.CartDTO;
import com.daxia.ogmall.model.Cart;
import com.daxia.ogmall.support.Page;

@Repository
public class CartDAO extends GenericDAOHibernate<Cart> {

    public List<Cart> find(CartDTO dto, Page page) {
        StringBuilder hql = new StringBuilder();
        List<Object> paras = new ArrayList<Object>();
        hql.append("From Cart n where 1 = 1 ");
        if (dto.getId() != null) {
            hql.append(" and n.id = ? ");
            paras.add(dto.getId());
        }
        if (dto.getUser() != null) {
        	if (dto.getUser().getId() != null) {
	            hql.append(" and n.user.id = ? ");
	            paras.add(dto.getUser().getId()); 
        	}
        }			
        if (dto.getProduct() != null) {
        	if (dto.getProduct().getId() != null) {
	            hql.append(" and n.product.id = ? ");
	            paras.add(dto.getProduct().getId());
        	}
        }			
        if(dto.getStatus() != null) {
        	hql.append(" and n.status = ? ");
        	paras.add(dto.getStatus());
        }
        return super.find(hql.toString(), paras.toArray(), page);
    }
    
    public int getCountByUser(Long userId) {
		String hql = "select count(*) from Cart where user.id = ?";
		return super.countByHql(hql, new Object[] {userId});
	}
    
    public int updateStatusAndCount(CartDTO cart) {  
    	String hql = "update Cart set quantity = ?,status = ? where id = ?";
    	return super.executeUpdate(hql, new Object[] {cart.getQuantity(),cart.getStatus(),cart.getId()});
    }
    
    public Cart findOne(CartDTO dto) {
		Page page = new Page();
		page.setPageSize(1);
		page.setPage(1);
		
		List<Cart> list = this.find(dto, page);
	    return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }
    
    @Override
    public void deleteById(Serializable id) {
    	getSession().delete(load(id));
    	//super.deleteById(id);
    }
}
